package io.github.enbool.controller;

import java.io.IOException;
import java.net.URLEncoder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import io.github.enbool.properties.QiniuProperties;
import lombok.Getter;
import lombok.Setter;

@RestController
public class FileController {

	@Autowired
	private QiniuProperties qiniuProperties;
	
	@PostMapping("/upload")
	public UploadRet upload(MultipartFile file) throws IOException {
		//构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone0());
		UploadManager uploadManager = new UploadManager(cfg);
		
		Auth auth = Auth.create(qiniuProperties.getAccessKey(), qiniuProperties.getSecretKey());
		String upToken = auth.uploadToken(qiniuProperties.getBucket());
		
		String fileName = file.hashCode() + '_' + file.getOriginalFilename();
	
        Response response = uploadManager.put(file.getInputStream(), fileName, upToken, null, null);
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

        String finalUrl = String.format("%s/%s", qiniuProperties.getDomainOfBucket(), URLEncoder.encode(putRet.key, "utf-8"));
	    
		return new UploadRet(finalUrl);
	}
}

@Getter
@Setter
class UploadRet{
	private String url;
	
	public UploadRet(String url) {
		this.url = url;
	}
}
